//
//  HLMessagelimitRequest.m
//  YueYue
//
//  Created by LiuYu on 2024/11/1.
//

#import "HLMessagelimitRequest.h"

@implementation HLMessagelimitResponse
{
    NSDate *_endTime;
    NSInteger _count;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _isLimit = 1;
        _limitMinute = 1;
        _limitMessageCount = 10;
    }
    return self;
}

- (BOOL)isNeedLimitWithHandler:(void (^)(BOOL))handler
{
    if (self.isLimit == NO) {
        return NO;// 不需要限制
    }
    
    _count++;
    NSLog(@"[b]当前消息数量 %zd", _count);
    
    NSDate *currentTime = [NSDate date];
    if (!_endTime) {
        NSLog(@"[b]开始");
        // 计算 N 分钟后的时间
        _endTime = [currentTime dateByAddingTimeInterval:self.limitMinute * 60];
        return NO;
    }
    
    // 比较当前时间和结束时间
    if ([currentTime compare:_endTime] == NSOrderedDescending) {
        // 限制时间结束，不需要限制消息
        NSLog(@"[b]限制时间到！！");
        // 开始新一轮计时
        _count = 0;
        _endTime = [currentTime dateByAddingTimeInterval:self.limitMinute * 60];
        handler(YES);
        return NO;
    } else {
        if (_count <= self.limitMessageCount) {
            NSLog(@"[b]未到达数量限制");
            return NO;
        } else {
            NSLog(@"[b]已经达到最大消息数！！！！");
            return YES; // 先定时间内，消息一经超出数量，限制
        }
    }
    
    return NO;
}

@end

@implementation HLMessagelimitRequest

- (NSString *)requestUrl
{
    return @"/app/msg/limit";
}

- (YTKRequestMethod)requestMethod
{
    return YTKRequestMethodGET;
}

- (HLMessagelimitResponse *)limitResponse
{
    HLMessagelimitResponse *res;
    NSDictionary *data = [self.result valueForKey:@"data"];
    if (![data isKindOfClass:[NSDictionary class]]){
        return res;
    }
    res = [HLMessagelimitResponse mj_objectWithKeyValues:data];
    return res;
}

@end
